from socket import *
import json
import time


"""
基于tcp sockets的通信
"""

class TcpClient():
    def __init__(self,ip="127.0.0.1",port=8088):
        self.message_count = 0
        self.server_ip_port = (ip,port)
        self.client_socket = socket(AF_INET, SOCK_STREAM)
        self.client_socket.connect(self.server_ip_port)
        
    def send_message(self,send_data):
        self.client_socket.send(send_data)
        self.message_count += 1
        print(f"tcp client sends No. {self.message_count} message!")
        
    def receive_message(self):
        while True:
            data = self.client_socket.recv(9000)
            data = data.decode("utf-8")
            if data:
                message = json.loads(data)
                print(f"server sent : {message}")
                self.message_count += 1
            else:
                print("no data")
                self.socket_close()
                break
        
    def socket_close(self):
        self.client_socket.close()
        print(f"The tcp client received {self.message_count} messages")
        
        
class TcpServer():
    def __init__(self,ip="127.0.0.1",port=8088):
        self.server_socket = socket(AF_INET, SOCK_STREAM)
        self.host_port = (ip, port)
        self.server_socket.bind(self.host_port)
        self.server_socket.listen(5)
        self.client_socket = None
        self.client_addr = None
        self.message_count = 0
        print(f"=================",{ip,port})
        
        self.__wait_client()
    
    def __wait_client(self):
        new_socket, client_addr = self.server_socket.accept()
        self.client_addr = client_addr
        self.client_socket = new_socket
        print(f"A client is connected! ip address : {self.client_addr}")
        
    def receive_message(self):
        re_data=self.client_socket.recv(1024)
        re_data.decode("utf-8")
        print(f"receives {re_data} from client")
    
    def send_message(self,send_data):
        self.client_socket.send(send_data)
        self.message_count += 1
        print(f"tcp server sends No. {self.message_count} message! -- {len(send_data)}")
        
    
    def socket_close(self):
        self.client_socket.close()
        self.server_socket.close()
        print(f"The tcp server sent {self.message_count} messages in total")
        
        
if __name__ == "__main__":
    tcp_server = TcpServer()
    for i in range(10):
        temp_dict = {"name":"Jim_"+str(i),"grade":i}
        json_message = json.dumps(temp_dict).encode("utf-8")
        tcp_server.send_message(json_message)
        time.sleep(1)
    
    tcp_server.socket_close()
            